package com.demo.service.app.service.impl;

import com.demo.service.app.pojo.*;
import com.demo.service.app.service.FanPorService;
import com.demo.service.app.util.SnowFlake;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.EAN;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class FanPorServiceImpl implements FanPorService {
    @Override
    public List<FanPor> getUser(String baseUrl) {
        List<FanPor> fanPorList = new ArrayList<>();
        String url = baseUrl+"/5795";
        for (int i=1; i<61; i++){
            if(i>1){
                url = baseUrl+"/5795/page/"+i;
            }
            //连接网站获取内容
            Document doc = null;
            try {
                doc = Jsoup.connect(url).get();
            } catch (IOException e) {
                log.error(e.getMessage());
            }
            Element content = doc.getElementsByClass("main-yy").first();
            //将获取的数据放置列表中
            Elements links = content.getElementsByTag("li");
            for (Element link : links) {
                FanPor fanPor = getFan(link);
                fanPorList.add(fanPor);
            }
        }
        return fanPorList;
    }

    @Override
    public List<FanPorArt> getArts(List<FanPor> fanPorList) {
        List<FanPorArt> fanPorArts = new ArrayList<>();

        int count=1;
        for(FanPor fanPor : fanPorList){
            log.info("正在处理第{}位，名称：{}，链接：{}。",String.valueOf(count),fanPor.getTitle(),fanPor.getUserHref());
            //读取详细信息
            Document doc = null;
            try {
                doc = Jsoup.connect(fanPor.getUserHref()).get();
            } catch (IOException e) {
                log.error(e.getMessage());
            }

            Element content = doc.getElementsByClass("p2main-r").first();
            Elements links = content.getElementsByTag("div");
            Element side = null;
            //找出符合条件的列表
            for(Element e:links){
                if("p2side".equals(e.attr("class"))){
                    side = e;
                }
            }
            //为空则无数据，跳过进入下一个
            if(side==null){
                count++;
                continue;
            }
            //解析详细信息
            Elements videos = side.getElementsByTag("hr");
            for(Element v : videos){
                //读取详情链接和图片链接
                Element a1 = v.nextElementSibling();
                String detailLink = a1.attr("href");
                String imgSrc = a1.selectFirst("img").attr("src");

                //读取标题
                Element a2 = a1.nextElementSibling();
                if(!a2.tagName().equals("a")){
                    a2 = a1.nextElementSibling().nextElementSibling();
                }
                if(!a2.tagName().equals("a")){
                    a2 = a1.nextElementSibling().nextElementSibling().nextElementSibling();
                }
                if(!a2.tagName().equals("a")){
                    a2 = a1.nextElementSibling().nextElementSibling().nextElementSibling().nextElementSibling();
                }
                String title = a2.attr("title");

                //读取code
                Element a3 = a2.nextElementSibling().nextElementSibling();
                String hashCode = StringUtils.isEmpty(a3.attr("title"))?"":a3.attr("title");

                FanPorArt fanPorArt = new FanPorArt();
                fanPorArt.setName(fanPor.getTitle());
                fanPorArt.setTitle(title);
                fanPorArt.setHashCode(hashCode);
                fanPorArt.setImgSrc(imgSrc);
                fanPorArt.setDetailLink(detailLink);

                fanPorArts.add(fanPorArt);
            }
            count++;
        }
        return fanPorArts;
    }

    @Override
    public List<Tag> getTags(String baseUrl){
        List<Tag> list = new ArrayList<>();
        Document doc = null;
        try {
            doc = Jsoup.connect(baseUrl).get();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        Elements sides = doc.select(".whole > .wrap > .wrap-l > .side");
        Elements hotTags = null;
        for(Element e : sides){
            if("HOT TAG".equals(e.getElementsByTag("p").first().text())){
                hotTags = e.getElementsByTag("li");
                break;
            }
        }
        for(Element e : hotTags){
            String name = e.getElementsByTag("a").first().text();
            String link = e.getElementsByTag("a").first().attr("href");

            Tag tag = new Tag();
            tag.setName(name);
            tag.setLink(baseUrl+link);
            list.add(tag);
        }
        return list;
    }

    @Override
    public List<TagResult> getTagResult(String tagName, String tagLink) {
        List<TagResult> tagResultList = new ArrayList<>();
        //获取总页数
        int totalPage = getTotalPage(tagLink);
        //开始读取数据
        String url = tagLink;
        for(int i=1; i<=totalPage; i++){
            log.info("正在处理标签：{},第{}页，。", tagLink, String.valueOf(i));
            if(i>1){
                url = tagLink+"/page/"+i;
            }
            Document doc = null;
            try {
                doc = Jsoup.connect(url).get();
            } catch (IOException e) {
                log.error(e.getMessage());
            }

            Element content = doc.selectFirst(".p2main-rr > .p2main-loop");
            Elements elements = content.getElementsByTag("li");

            for(Element e : elements){
                Element aTag = e.getElementsByTag("a").last();
                String title = aTag.attr("title");
                String href = aTag.attr("href");
                String imgSrc = aTag.selectFirst("p > img").attr("src");

                TagResult tagResult = new TagResult();
                tagResult.setTag(tagName);
                tagResult.setTitle(title);
                tagResult.setDetailLink(href);
                tagResult.setImgLink(imgSrc);

                tagResultList.add(tagResult);
            }
        }
        return tagResultList;
    }

    private FanPor getFan(Element link){
        //读取主要信息
        Element aTab = link.getElementsByTag("a").first();
        Element imgTab = aTab.getElementsByTag("img").first();

        String userHref = aTab.attr("href");
        String title = aTab.attr("title");;
        String imgSrc = imgTab.attr("src");

        //添加至列表
        FanPor fanPor = new FanPor();
        fanPor.setTitle(title);
        fanPor.setUserHref(userHref);
        fanPor.setImgSrc(imgSrc);

        return fanPor;
    }

    private int getTotalPage(String tagLink){
        Document doc = null;
        int totalPage = 0;
        try {
            doc = Jsoup.connect(tagLink).get();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        if(doc==null){
            return 0;
        }
        Element pageElement = doc.selectFirst(".p2main-rr > .page");
        if(pageElement==null){
            return 1;
        }
        Element lastPage = pageElement.getElementsByTag("a").last().previousElementSibling();
        totalPage = Integer.parseInt(lastPage.getElementsByTag("span").first().text());
        return totalPage;
    }
}
